﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using AlertSystem;
using AlertSystem.Dab.LK;
using LLoger;
using System.Windows.Forms;
using DataGrid = System.Windows.Controls.DataGrid;

namespace AlertClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private AlertLoadService svc;
        private NotifyIcon _notifyIcon = null;
        private DispatcherTimer _checkAlertsTimer = new DispatcherTimer();
        private bool _canClose = false;

        public MainWindow()
        {
            InitializeComponent();

            Closing += new System.ComponentModel.CancelEventHandler(MainWindow_Closing);
            Closed += new EventHandler(MainWindow_Closed);
            Deactivated += new EventHandler(MainWindow_Deactivated);
            AlertLoadService.GonfigureService("AlertSystem.config", new FileLogWriter("events.log", 0));
            svc = AlertLoadService.Instance;
            //svc.RegisterProvider(new DabOrdersLoadProvider(), new LkOrdersLoadParser());
            //svc.RegisterProvider(new LkKeysLoadProvider(), new LkKeysLoadParser());

            InitTrayIcone();
            InitCheckTimer();
            Close();
        }

        void MainWindow_Deactivated(object sender, EventArgs e)
        {
            _checkAlertsTimer.IsEnabled = true;
        }

        void MainWindow_Closed(object sender, EventArgs e)
        {
            _notifyIcon.Visible = false;
            _notifyIcon.Dispose();
        }

        void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            _canClose |= Keyboard.Modifiers == ModifierKeys.Control;

            if (!_canClose)
            {
                this.Hide();
                e.Cancel = true;
                this.ShowInTaskbar = false;
            }
        }

        private void InitCheckTimer()
        {
            SetTimerInterval(Properties.Settings.Default.CheckTimerInterval);
            _checkAlertsTimer.Tick += _checkAlertsTimer_Tick;
            _checkAlertsTimer.IsEnabled = true;
        }

        void _checkAlertsTimer_Tick(object sender, EventArgs e)
        {
            if (this.IsActive)
            {
                _checkAlertsTimer.IsEnabled = false;
                return;
            }
            svc.StartLoadAsinch(RefreshView);

            ShowTrayNotify();
            SetTimerInterval(Properties.Settings.Default.CheckTimerInterval);

        }

        private void ShowTrayNotify()
        {
            _notifyIcon.BalloonTipIcon = ToolTipIcon.Info;
            _notifyIcon.BalloonTipTitle = "Ожидают внимания:";


            string msg = "";
            foreach (var listType in svc.AlertsAgregator.AlertList)
            {
                var list = svc.AlertsAgregator.GetAlertList(listType);
                var cnt = list.Count();

                if (cnt == 0)
                    continue;

                msg += list.First().SysAlertName + " - " + cnt + "\r\n";
            }

            
            _notifyIcon.BalloonTipText = msg;
            _notifyIcon.ShowBalloonTip(2000);
        }

        private void InitTrayIcone()
        {
            _notifyIcon = new NotifyIcon();
            _notifyIcon.MouseDoubleClick += _notifyIcon_MouseDoubleClick;
            _notifyIcon.BalloonTipClicked += new EventHandler(_notifyIcon_BalloonTipClicked);
            _notifyIcon.Visible = true;
            _notifyIcon.Icon = Properties.Resources.Ampoule;

            InitNotifyMenu();
        }

        void _notifyIcon_BalloonTipClicked(object sender, EventArgs e)
        {
            SetTimerInterval(Properties.Settings.Default.SlipCheckTimer);
            this.ShowWindow();
        }

        private void InitNotifyMenu()
        {
            var menu = new System.Windows.Forms.ContextMenu();
            menu.MenuItems.Add("Выход", (sender, args) =>
            {
                _canClose = true;
                Close();
            });

            _notifyIcon.ContextMenu = menu;
        }
        
        private void SetTimerInterval(int msec)
        {
            _checkAlertsTimer.Interval = new TimeSpan(0, 0, msec);
        }

        void _notifyIcon_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            ShowWindow();
        }

        private void ShowWindow()
        {
            this.Show();
            this.ShowInTaskbar = true;
        }

        private void RefrashButton_Click(object sender, RoutedEventArgs e)
        {
            svc.StartLoadAsinch(RefreshView);
        }

        private void RefreshView()
        {
            foreach (var itm in svc.AlertsAgregator.AlertList)
            {
                var list = svc.AlertsAgregator.GetAlertList(itm);

                RefreshTabItem(list);
            }

            mainTab.Visibility = System.Windows.Visibility.Visible;
        }

        private void RefreshTabItem(IEnumerable<IAlertItem> alertItems)
        {
            if (alertItems == null) throw new ArgumentNullException("alertItems");

            if (!alertItems.Any())
                return;

            TabItem tab = null;
            foreach (var item in mainTab.Items)
            {
                var tabItem = item as TabItem;

                if (tabItem.Tag != null && tabItem.Tag == alertItems.First().SysAlertName)
                {
                    tab = tabItem;
                    break;
                }
            }

            tab = tab ?? AddTabItem(alertItems);


            var grid = ((DataGrid)tab.Content);
            grid.ItemsSource = alertItems;

            grid.Items.Refresh();
        }

        private TabItem AddTabItem(IEnumerable<IAlertItem> alertItems)
        {
            TabItem tab;
            var alertItem = alertItems.First();
            tab = new TabItem();

            tab.Tag = alertItem.SysAlertName;
            var dg = new DataGrid();
            tab.Content = dg;
            dg.AutoGenerateColumns = true;
            tab.Header = alertItem.SysAlertName;
            mainTab.Items.Add(tab);
            return tab;
        }


    }
}
